<template>
  <BoTable
    :columns="columns"
    :request="getPushList"
    ref="tableRef"
    row-key="id"
    :row-selection="rowSelection"
    :show-index="true"
  >
    <template #toolbars>
      <Space :size="8">
        <Button type="primary" @click="onAdd"> 新增静默策略 </Button>
        <Button :disabled="!selectKeys?.length" @click="onDelete()"
          >删除</Button
        >
      </Space>
    </template>
  </BoTable>
  <FormModal :columns="items"> </FormModal>
</template>
<route lang="json">
{
  "name": "silence",
  "meta": {
    "title": "告警静默"
  }
}
</route>
<script setup lang="tsx">
import { computed, ref } from 'vue';
import { useFormModal } from '@boeyo/hooks';
import { useDicts } from '@boeyo/portal';
import { BoFormProps, BoTable, BoTableProps } from '@boeyo/ui';
import {
  Button,
  CheckboxGroup,
  Modal,
  RadioButton,
  RadioGroup,
  RangePicker,
  Space,
  Switch,
  TimePicker,
  message,
} from 'ant-design-vue';
import { FormItem, FormItemRest } from 'ant-design-vue/es/form';
import { addPush, deletePush, getPushList, updatePush } from './api';

const tableRef = ref();
const selectKeys = ref<any[]>([]);
const rowSelection = computed<BoTableProps['rowSelection']>(() => {
  return {
    selectedRowKeys: selectKeys.value,
    onChange(values, all) {
      selectKeys.value = values;
    },
  };
});

const dictArr = ['silence_type'];
const { silenceTypeEnum, silenceTypeOptions } = useDicts(dictArr);

const columns = computed<BoTableProps['columns']>(() => [
  {
    title: '策略名称',
    dataIndex: 'name',
  },
  {
    title: '静默类型',
    dataIndex: 'name',
    hideInSearch: true,
    valueEnum: silenceTypeEnum.value,
  },
  {
    title: '匹配标签',
    dataIndex: 'name',
    hideInSearch: true,
    valueEnum: silenceTypeEnum.value,
  },
  {
    title: '启用静默策略',
    dataIndex: 'count',
    hideInSearch: true,
    customRender({ record }) {
      return (
        <Switch
          checked={record.status}
          checked-value='0'
          un-checked-value='1'
          onChange={(checked) => onSwitch(checked, record)}
        ></Switch>
      );
    },
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    fixed: 'right',
    actions() {
      return [
        {
          text: '详情',
          onClick(record) {
            onView(record);
          },
        },
        {
          text: '删除',
          onClick(record) {
            onDelete(record);
          },
        },
      ];
    },
  },
]);

const weekOptions = [
  {
    label: '星期日',
    value: '0',
  },
  {
    label: '星期一',
    value: '1',
  },
  {
    label: '星期二',
    value: '2',
  },
  {
    label: '星期三',
    value: '3',
  },
  {
    label: '星期四',
    value: '4',
  },
  {
    label: '星期五',
    value: '5',
  },
  {
    label: '星期六',
    value: '6',
  },
];
const items = computed<BoFormProps['columns']>(() => [
  {
    title: '策略名称',
    dataIndex: 'name',
    valueType: 'input',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请输入策略名称',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请输入策略名称',
    },
  },
  {
    title: '静默类型',
    dataIndex: 'type',
    valueType: 'radio',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请输入策略名称',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请输入策略名称',
      options: silenceTypeOptions.value,
    },
    formItemRender(record) {
      return (
        <FormItem
          label='静默类型'
          name='type'
          rules={[{ required: true, message: '请选择静默类型' }]}
        >
          <RadioGroup v-model:value={record.type}>
            {silenceTypeOptions.value.map((item) => {
              return <RadioButton value={item.value}>{item.label}</RadioButton>;
            })}
          </RadioGroup>
        </FormItem>
      );
    },
  },
  {
    title: '静默时段',
    dataIndex: 'times',
    valueType: 'dateRange',
    fieldProps: {
      showTime: true,
    },
    formItemRender(record) {
      return (
        <FormItemRest>
          <FormItem
            label='静默类型'
            name='type'
            rules={[{ required: true, message: '请选择静默类型' }]}
          >
            {record.type == '0' ? (
              <RangePicker
                v-model:value={record.timeRange}
                format='YYYY-DD-MM HH:mm:ss'
                valueFormat='YYYY-DD-MM HH:mm:ss'
              ></RangePicker>
            ) : (
              <div>
                <FormItemRest>
                  <CheckboxGroup
                    v-model:value={record.timeList}
                    options={weekOptions}
                  ></CheckboxGroup>
                  <div class='my-2 mr-2'>
                    <TimePicker
                      v-model:value={record.time1}
                      format='HH:mm'
                      valueFormat='HH:mm'
                    ></TimePicker>
                  </div>
                  <div>
                    <TimePicker
                      v-model:value={record.time2}
                      format='HH:mm'
                      valueFormat='HH:mm'
                    ></TimePicker>
                  </div>
                </FormItemRest>
              </div>
            )}
          </FormItem>
        </FormItemRest>
      );
    },
  },
  {
    title: '是否启用',
    dataIndex: 'status',
    valueType: 'switch',
  },
]);

const { FormModal, open } = useFormModal({
  size: 'small',
  column: 1,
});

const onSwitch = async (checked, record) => {
  console.log(checked, record, 'switch');

  const params = {
    id: record.id,
    status: checked,
  };
  await updatePush(params);
  tableRef.value.refresh();
};

const onView = (record) => {
  const noticeObj = record.noticeObj?.split(',');
  const noticeType = record.noticeType?.split(',');
  open({
    title: (type) => (type === 'info' ? '详情' : '编辑'),
    modalType: 'info',
    request: async (params: any) => {
      console.log(params, 'params');
      await updatePush(params);
      tableRef.value.refresh();
    },
    defaultValue: {
      ...record,
      noticeObj,
      noticeType,
    },
  });
};

const onAdd = async () => {
  open({
    title: '新增',
    defaultValue: {
      status: '1',
      type: '0',
      timeRange: [],
      timeList: [],
      time1: '',
      time2: '',
    },
    request: async (params: any) => {
      console.log(params, 'params');
      await addPush(params);
      tableRef.value.refresh();
    },
  });
};

const onDelete = async (record = null) => {
  const ids = record ? record.id : selectKeys.value.join();
  console.log(ids, 'ids');
  if (!ids) return message.info('请选择要删除的数据');
  Modal.confirm({
    title: '系统提示',
    content: `确定删除当前选中项数据吗?`,
    onOk: async () => {
      await deletePush(ids);
      message.success('操作成功');
      tableRef.value.refresh();
    },
  });
};
</script>

<style lang="scss" scoped></style>
